package com.ymatou.iapi.delivery.service;

import java.math.BigDecimal;

import com.google.common.collect.Lists;
import com.ymatou.iapi.delivery.parameter.DeliveryInfo;
import com.ymatou.iapi.delivery.parameter.DeliveryReq;
import com.ymatou.iapi.delivery.parameter.ImportDeliveryInfo;
import com.ymatou.iapi.optrade.parameter.enums.LogisticsTypeEnum;
import com.ymatou.iapi.optrade.parameter.utill.Utils;
import com.ymatou.iapi.optrade.resp.TradingServiceResp;
import com.ymt.base.YmatouEasyCall;
import com.ymt.core.tool.Logger;
import com.ymttest.business.service.YMTTrading.TradingCallService;
import com.ymttest.business.service.YMTTrading.TradingPlaceOrderCallService;
import com.ymttest.database.sharding.db.ext.model.DeliveryPo;
import com.ymttest.database.sharding.db.sqlwapper.OrderWapper;
import com.ymttest.utils.TestDataManager;
import com.ymttest.utils.YMTDateUtil;

public class DeliveryService {

	private static OrderWapper orderWapper = new OrderWapper();

	public static final boolean isWriteSqlServer = false;

	/*	 
	 * 	  拼邮
		 Y047 新顺丰（NSF）
		 Y013 顺丰速运（SF-Express）
		 Y068 洋码头官方合作物流
		 Y078 洋码头官方合作物流
		 
		 认证直邮
		 Y013 EMS（国内）
		 Y013 顺丰速运（SF-Express）
		 		 
		 */

	public static final String YmtExpressCode1 = "Y013";

	public static final String YmtExpressCode2 = "Y068";

	public static final String YmtExpressCode3 = "Y047";
	
	public static final String YmtExpressCode4 = "Y078";
	
	public static final String YmtExpressCode5 = "Y037";

	/**
	 * 第三方物流通知 码头 物流签收状态通知接口
	 */
	public static void saveLogisticsInfo(String billNo, String sighTime) {

		YmatouEasyCall saveLogisticsInfoCall = new YmatouEasyCall("", "POST",
				"JSON");
		StringBuffer saveLogisticsInfoString = new StringBuffer();

		saveLogisticsInfoString.append("{");

		saveLogisticsInfoString
				.append(String
						.format("\"bizContent\": \"{\\\"cpCode\\\":\\\"Y072\\\",\\\"mailNo\\\":\\\"%s\\\",\\\"logisticsGmtModified\\\":\\\"%s\\\",\\\"bizKey\\\":\\\"%s\\\",",
								billNo, sighTime, billNo));

		saveLogisticsInfoString
				.append("\\\"logisticsStatusDesc\\\":\\\"已签收\\\",\\\"lastLogisticDetail\\\":\\\"autotest 已签收 签收人：家人\\\",\\\"logisticsStatus\\\":\\\"SIGN\\\"}\",");

		saveLogisticsInfoString.append(String.format("\"billNo\": \"%s\",",
				billNo));

		saveLogisticsInfoString.append("\"platform\": 4}");

		saveLogisticsInfoCall
				.setUrl("http://recvlogistics.iapi.ymatou.com/Express/SaveLogisticsInfo");

		saveLogisticsInfoCall.setData(saveLogisticsInfoString.toString());

		Logger.comment("第三天通知物流签收");

		try {
			saveLogisticsInfoCall.callService();

		} catch (Exception e) {

			e.printStackTrace();
		}

	}
	
	/**
	 * 插入一条订单物流发货数据
	 */
	public static void saveDeliveryByReqAndInfo(long orderId, long sellerId,
			int logisticsType, DeliveryInfo deliveryInfo) {

		DeliveryPo deliveryPo = new DeliveryPo();

		deliveryPo.setBillNo(deliveryInfo.getBillNo());
		deliveryPo.setOrderId(orderId);
		deliveryPo.setYmtExpressCode(deliveryInfo.getYmtExpressCode());
		deliveryPo.setSellerId(sellerId);

		deliveryPo.setRealDeliveryArea(deliveryInfo.getRealDeliveryArea());
		deliveryPo.setSource(deliveryInfo.getDeliverySource());
		deliveryPo.setSection(deliveryInfo.getDeliverySection());
		deliveryPo.setExpressName(deliveryInfo.getExpressName());
		deliveryPo.setLogisticsType(logisticsType);
		deliveryPo.setOfficalLogistics(false);
		deliveryPo.setSourceTrack(false);

		deliveryPo.setDeleted(Boolean.FALSE);
		deliveryPo.setPackageType(Utils.falseIfNull(deliveryInfo.getAuthenticatePackage()) ? 1 : null);

		orderWapper.insertDeliveryPo(deliveryPo);

	}
	
	/**
	 * 插入一条订单物流发货数据
	 */
	public static void saveDeliveryByReqAndInfo(long orderId, long sellerId,
			int logisticsType, ImportDeliveryInfo deliveryInfo) {

		DeliveryPo deliveryPo = new DeliveryPo();

		deliveryPo.setBillNo(deliveryInfo.getBillNos().get(0));
		deliveryPo.setOrderId(orderId);
		deliveryPo.setYmtExpressCode(deliveryInfo.getYmtExpressCode());
		deliveryPo.setSellerId(sellerId);

		deliveryPo.setRealDeliveryArea(deliveryInfo.getRealDeliveryArea());
		deliveryPo.setSource(deliveryInfo.getDeliverySource());
		deliveryPo.setSection(deliveryInfo.getDeliverySection());
		deliveryPo.setExpressName(deliveryInfo.getExpressName());
		deliveryPo.setLogisticsType(logisticsType);
		deliveryPo.setOfficalLogistics(false);
		deliveryPo.setSourceTrack(false);

		deliveryPo.setDeleted(Boolean.FALSE);
		deliveryPo.setPackageType(Utils.falseIfNull(deliveryInfo.getAuthenticatePackage()) ? 1 : null);

		orderWapper.insertDeliveryPo(deliveryPo);

	}
	
	public static void deleteDeliverByBillNo(String billNo) {
		
		orderWapper.deleteDeliveryBybillNo(billNo);
	}

	/**
	 * 创建一个拼邮,已接单的订单
	 * @return
	 * @throws Exception 
	 */
	public static TradingServiceResp placeOrder() throws Exception {

		TradingServiceResp placeOrderResp = TradingPlaceOrderCallService
				.placeOrderWithLogisticsType(LogisticsTypeEnum.OVERSEAS_DELIVERY);

		long sellerId = placeOrderResp.getOrderList().get(0).getSellerId();

		long orderId = placeOrderResp.getOrderList().get(0).getOrderId();

		long userId = placeOrderResp.getUserId();

		long tradingId = placeOrderResp.getTradingId();

		BigDecimal useAccountAmount = placeOrderResp.getPayableAmount();

		TradingCallService.payOrder(userId, useAccountAmount, tradingId);

		TradingCallService.sellerAcceptOrder(sellerId, orderId);

		return placeOrderResp;
	}

	/**
	 * callDelivery
	 * @param orderId
	 * @param sellerId
	 * @param deliverySection
	 */
	public static DeliveryInfo callDelivery(long orderId, long sellerId,
			int deliverySection) {

		DeliveryReq deliveryReq = new DeliveryReq();

		DeliveryCall deliveryCall = new DeliveryCall();

		DeliveryInfo dInfo = new DeliveryInfo();

		dInfo.setOrderId(orderId);

		dInfo.setBillNo(TestDataManager.getRandomNum(9));

		//发货节点、1国际段,2转运段,3国内段
		dInfo.setDeliverySection(1);
		dInfo.setDeliverySource(1);

		dInfo.setExpressName("sf");
		dInfo.setYmtExpressCode(YmtExpressCode1);

		//dInfo.setRealDeliveryArea(realDeliveryArea);

		deliveryReq.setDeliveryInfos(Lists.newArrayList(dInfo));

		deliveryReq.setSellerId(sellerId);

		deliveryCall.setData(deliveryReq);

		try {
			deliveryCall.callService();

			Thread.sleep(5000);

		} catch (Exception e) {
			e.printStackTrace();
		}

		return dInfo;

	}
	
	/**
	 * 是否鉴别中心发过货
	 * 
	 * @param orderId
	 */
	public static Boolean isAuthenticateDelivery(Long orderId) {

		DeliveryPo deliveryPo = orderWapper
				.selectDeliveryByAuthenticateDelivery(orderId);

		return null == deliveryPo ? false : true;
	}

	public static void main(String... args) {

		DeliveryService.saveLogisticsInfo(TestDataManager.getRandomNum(6),
				YMTDateUtil.getBeforeOrNextDay(-10, YMTDateUtil.YMDHMS));
	}
}
